package com.miyake.client.datamanage.plugin;

import java.util.List;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.miyake.client.DoctorsUserService;
import com.miyake.client.tools.OkCancelDialog;
import com.miyake.client.tools.ShowDialog;
import com.miyake.client.tools.SmallButton;

public class MyFilePluginChooser extends OkCancelDialog {

	private ListBox combo;
	private String selectedKey;
	
	@Override
	protected Widget getContent() {
		VerticalPanel panel = new VerticalPanel();
		combo = new ListBox();
		panel.add(new SmallButton("Plugin Market", new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				final FilePluginDialog dlg = new FilePluginDialog();
				new ShowDialog() {

					@Override
					protected void onOK(String text) {
						addFilePlugin(dlg.getSelectedKey());
					}

					@Override
					protected DialogBox getDialogBox() {
						return dlg;
					}
					
				};
			}
		}));
		panel.add(combo);
		updatePluginList();
		return panel;
	}

	private void updatePluginList() {
		

		DoctorsUserService.Util.getInstance().getFilePluginList(new AsyncCallback<List<PluginProperty>>() {

			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(List<PluginProperty> result) {
				combo.clear();
				for (PluginProperty p : result) {
					combo.addItem(p.getName(), p.getKey());
				}
				combo.addChangeHandler(new ChangeHandler() {
					@Override
					public void onChange(ChangeEvent event) {
						selectedKey = combo.getValue(combo.getSelectedIndex());
					}
				});
				selectedKey = combo.getValue(combo.getSelectedIndex());
			}
			
		});
	}
	
	private void addFilePlugin(String selectedKey) {
		DoctorsUserService.Util.getInstance().addFilePlugin(selectedKey, new AsyncCallback<Void>() {
			@Override
			public void onFailure(Throwable caught) {

			}

			@Override
			public void onSuccess(Void result) {
				updatePluginList();
			}
		});
	}

	public String getSelectedKey() {
		return selectedKey;
	}
	
}
